<?php
namespace App\Http\Controllers\Admin\App;

use App\Services\Admin\CategoryService;
use App\Utilities\JiugeForm;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{
    /**
     * 用户注册属性
     */

    protected $view = 'admin.app.cate.';//视图前缀
    protected $url = 'cate';//路由前缀
    protected $model;
    protected $formElementArr = [//表单元素
        //array(表单选项,中文名称,name字段名称,表单提示,js验证规则)
        array(1,'属性名称','name','扩展名称，2-20字符',1),
        array(5,'所属父级','pid','父级分类',6),
    ];
    protected $fieldShowArr = [
        'id' => 'ID',
        'name' => '属性名称',
        'pid' => '所属父级',
        'createTime' => '创建时间',
    ];

    public function __construct()
    {
        parent::__construct();
        $this->prefix_url = $this->prefix_url.'/'.$this->url;
        $this->model = new CategoryService();
        view()->share('prefix_url',$this->prefix_url);
        view()->share('jiugeForm',new JiugeForm($this->prefix_url));
    }

    public function index(Request $request)
    {
        $pid = isset($request->pid) ? $request->pid : 0;
        $models = $this->model->getIndex($pid);
        return view($this->view.'index',array(
            'datas' => $models,
            'parents' => $this->model->getParents(),
            'pid' => $pid,
        ));
    }

    public function create()
    {
        return view($this->formView.'edit',array(
            'sels' => $this->formElementArr,
            'options' => array(
                'pid' => $this->model->getParents(),
            ),
        ));
    }

    public function store(Request $request)
    {
        $data = $this->getData($request);
        $this->model->add($data);
        return redirect($this->prefix_url);
    }

    public function edit($id)
    {
        return view($this->formView.'edit',array(
            'sels' => $this->formElementArr,
            'options' => array(
                'pid' => $this->model->getParents(),
            ),
            'data' => $this->model->getOne($id),
        ));
    }

    public function update(Request $request,$id)
    {
        $model = $this->model->getOne($id);
        $data = $this->getData($request);
        $this->model->modify($data,$id);
        return redirect($this->prefix_url);
    }

    public function getData(Request $request)
    {
        $name = $request->name;
        $pid = $request->pid;
        if (!$name) {
            echo "<script>alert('数据不全！');history.go(-1);</script>"; exit;
        }
        return array(
            'name' => $name,
            'pid' => $pid,
        );
    }

    public function getModel($id)
    {
        $model = $this->model->getOne($id);
        if (!$model) {
            echo "<script>alert('记录不存在！');history.go(-1);</script>"; exit;
        }
        return $model;
    }
}
